<?php
namespace Home\Controller;
use Think\Controller;
class ImgsModelController extends Controller {

	private $m = '';
	public function _initialize(){
		if($this->m ==''){
			$this->m = M('Imgs');
		}
	}

	//获取全部图片列表
	public function get_imgs($fields='',$where='',$order = 'imgs_id desc',$pcount = 10){
		return Get_Fpage($this->m,$fields,$where,$order,$pcount);
	}


	//添加图片
	public function add(){
		$aid = I('post.album_id');
		if(!$aid){
			exit('e1');	//无效的相册id
		}
		//var_dump($_FILES);exit;
    	$upload = new \Think\Upload();    
    	$upload->maxSize   =     3145728 ;    
    	$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');   
    	$upload->rootPath  = 	 C('album_img_dir');
    	$upload->savePath  =     $aid.'/';  
    	$upload->autoSub = false;
    	//var_dump($upload);exit;
    	$info = $upload->upload();
    	if($info) {
    		//print_r($info);
    		//echo $info['savepath'].$info['savename'];
    		$url = $info['img']['savepath'].$info['img']['savename'];
    		$data['imgs_aid'] = $aid;
    		$data['imgs_src'] = $url;
    		$data['imgs_ctime'] = time();
    		if($this->m->create($data)){
    			$st = $this->m->add();
    			if($st > 0){
    				echo 'ok';
    				exit;
    			}
    		}
    	}
   		echo 'err'; 
   		//dump($this->error($upload->getError()));
	}



    //图片的删除
    public function del(){
        $pid = I('post.pid');
        $data = $this->get_info($pid);
        $path = C('album_img_dir').$data['imgs_src'];
        $st = $this->m->delete($pid);
        if($st > 0){
            echo 'ok';
            unlink($path);
        }else{
            echo 'err';
        }
    }


    //图片删除(多选)
    public function dels(){
        $pids = I('post.pids');
        $data = $this->m->select($pids);
        $st = $this->m->delete($pids);
        if($st > 0){
            foreach($data as $v){
                $path = C('album_img_dir').$v['imgs_src'];
                unlink($path);
            }
            echo 'ok';

        }
    }

   // 根据相册id删除相册下所有图片
    public function del_album_pics($aid){
        $st = $this->m->where(array('imgs_aid'=>$aid))->delete();
        return $st;
    }


    //根据图片id获取图片的信息
    public function get_info($pid){
        $data = $this->m->find($pid);
        if($data){
            return $data;
        }
    }


    //获取指定相册的图片(分页)
    public function get_album_pics($aid){
        if(!$aid){
            exit;
        }else{
            $where['imgs_aid'] = $aid;
        }
      //  return $this->m->where(array('imgs_aid'=>$aid))->select();
       return Get_Fpage($this->m,$fields='',$where,$order = 'imgs_id desc',$pcount = 6);
    }


    //根据指定相册的全部图片
    public function get_album_pics_all($aid){
        if(!$aid){
            exit;
        }
        $data = $this->m->where(array('imgs_aid'=>$aid))->select();
        if($data){
            return $data;
        }
    }
}